package com.ifcreate.infowell.sys.conf;

import com.ifcreate.infowell.common.annotation.NoLogin;
import com.ifcreate.infowell.common.util.JsonResult;
import com.ifcreate.infowell.common.util.JwtUtils;
import com.ifcreate.infowell.sys.util.SysContextUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author chenzedeng
 * @Email yustart@foxmail.com
 * @Create 2020-07-31 3:16 下午
 */
public class SysWebInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        NoLogin annotation = null;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(NoLogin.class);
        }
        if (annotation != null) {
            return true;
        }

        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(jwtUtils.getHeader());
        }

        //凭证为空
        if (StringUtils.isBlank(token)) {
            response.getWriter().print(JsonResult.error("token not blank", 401).toJson());
            return false;
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if (claims == null || jwtUtils.isTokenExpired(claims.getExpiration())) {
            response.getWriter().print(JsonResult.error("token expired", 401).toJson());
            return false;
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(SysContextUtil.AppContextUtilUserKey, claims.getSubject());
        request.getSession().setAttribute(SysContextUtil.AppContextUtilUserKey, claims.getSubject());
        return true;
    }
}
